<?php
/*
 * 分类级别管理
 * @package    auto
 * @author     Mark
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: 373f8e8cefa1f43cb00d4a5ba482ce5463b0c368 $
 */
defined('IN_IXDCW') or exit('Access Denied');
/**
 * 车型库级别的操作表, 增删改
 * Class AutoRank
 */
class AutoCategoryModule extends BasicModule {


	/** @var int Auto Rank id */
	private $_arid;

	/** @var array|String 分类 */
	private $_category = array();

	/** @var  当前操作的类型名称 */
	private $_typename;

	/** @var string 操作的数据表 */
	private $_table;


	/**
	 * 构造函数
	 * @param int $arid
	 * @param     $typename
	 */
	function __construct($arid = 0, $typename = 0) {
		parent::__construct();
		global $RANK;
		$this->_arid     = $arid;
		$this->_typename = $typename;
		if (!array_key_exists($typename, AutoCategory::getTypes())) {
			msg('类型不在输入范围之内, 请重新检查输入类型!');
		}
		if (!isset($RANK)) $RANK = AutoCategory::getCache($this->_typename);
		$this->_category = $RANK;
		$this->_table    = Table::name(Table::NAME_AUTO_CATEGORY);
	}


	/**
	 * 获取当前的操作项的ID
	 * @return int
	 */
	public function getArid() {
		return $this->_arid;
	}

	/**
	 *
	 */
	public function getTypename() {
		return $this->_typename;
	}

	public function set($post) {
		global $DT_TIME;
		if ($this->_arid) {
			$post['edittime'] = $DT_TIME;
		} else {
			$post['addtime']  = $DT_TIME;
			$post['edittime'] = $DT_TIME;
		}
		return $post;
	}

	/**
	 * 添加分级
	 * @param $rank
	 * @return bool
	 */
	function add($rank) {
		$rank = $this->set($rank);

		$rank['letter']   = Filter::vletter($rank['letter']);
		$rank['typename'] = $this->_typename;
		$this->_db->query(Sql::insert($this->_table, $rank));
		$this->_arid = $this->_db->insertId();
		if ($rank['parentid']) {
			$rank['arid']                  = $this->_arid;
			$this->_category[$this->_arid] = $rank;
			$arrparentid                   = $this->getArrParentid($this->_arid, $this->_category);
		} else {
			$arrparentid = 0;
		}
		$nickname = $rank['nickname'] ? $rank['nickname'] : $this->_arid;
		$this->_db->query("UPDATE {$this->_table} SET listorder=$this->_arid,nickname='$nickname',arrparentid='$arrparentid' WHERE arid=$this->_arid");
		return true;
	}

	/**
	 * 编辑
	 * @param $rank
	 * @return bool
	 */
	function edit($rank) {
		$rank           = $this->set($rank);
		$rank['letter'] = Filter::vletter($rank['letter']);
		$rank['arid']   = $this->_arid;
		if ($rank['parentid']) {
			$this->_category[$this->_arid] = $rank;
			$rank['arrparentid']           = $this->getArrParentid($this->_arid, $this->_category);
		} else {
			$rank['arrparentid'] = 0;
		}
		$rank['linkurl'] = '';
		if ($rank['typename'] == AutoCategory::TYPE_RANK) {
			$rank['linkurl'] = $this->_genUrl($rank['level'], $rank);
		}
		$sql = Sql::update($this->_table, $rank, "arid=$this->_arid");
		$this->_db->query($sql);
		return true;
	}

	/**
	 * 删除
	 * @param $arids
	 * @return bool
	 */
	function delete($arids) {
		if (is_array($arids)) {
			foreach ($arids as $arid) {
				if (isset($this->_category[$arid])) $this->delete($arid);
			}
		} else {
			$arid = $arids;
			if (isset($this->_category[$arid])) {
				$sql = "DELETE FROM {$this->_table} WHERE arid=$arid";
				$this->_db->query($sql);
				$arrchildid = $this->_category[$arid]['arrchildid'] ? $this->_category[$arid]['arrchildid'] : $arid;
				$this->_db->query("DELETE FROM {$this->_table} WHERE arid IN ($arrchildid)");
			}
		}
		return true;
	}

	/**
	 * 更新
	 * @param $category
	 * @param $arids
	 * @return bool
	 */
	function update($category, $arids = array()) {
		if (!is_array($category)) return false;
		foreach ($category as $k => $v) {
			if (!empty($arids)) {
				if (!in_array($k, $arids)) {
					continue;
				}
			}
			if (!$v['name']) continue;
			$v['parentid'] = intval($v['parentid']);
			if ($k == $v['parentid']) continue;
			if ($v['parentid'] > 0 && !isset($this->_category[$v['parentid']])) continue;
			$v['listorder'] = intval($v['listorder']);
			$v['level']     = intval($v['level']);
			$v['typename']  = strval($this->_typename);
			$v['letter']    = preg_match("/^[a-z0-9]{1}+$/i", $v['letter']) ? strtolower($v['letter']) : '';
			$v['nickname']  = $this->getNickname($v['nickname'], $k);
			if (!$v['nickname']) $v['nickname'] = $k;
			$this->_db->query("UPDATE {$this->_table} SET name='$v[name]',parentid='$v[parentid]',listorder='$v[listorder]',style='$v[style]',level='$v[level]',letter='$v[letter]',nickname='$v[nickname]' WHERE arid=$k ");

		}
		return true;
	}

	/**
	 * 分类修复并缓存
	 * @return bool
	 */
	function repair() {
		$query = $this->_db->query("SELECT * FROM {$this->_table} where typename='$this->_typename' ORDER BY listorder,arid");
		$RANK  = array();
		while ($r = $this->_db->fetchArray($query)) {
			$RANK[$r['arid']] = $r;
		}
		$childs = array();
		foreach ($RANK as $arid => $rank) {
			$RANK[$arid]['arrparentid'] = $arrparentid = $this->getArrParentid($arid, $RANK);
			$RANK[$arid]['nickname']    = $nickname = preg_match("/^[0-9a-z_\-\/]+$/i", $rank['nickname']) ? $rank['nickname'] : $arid;
			$sql                        = "nickname='$nickname',arrparentid='$arrparentid'";
			$pLevel                     = substr_count($arrparentid, ',');
			$sql .= ", level=$pLevel";
			// gen Url
			if ($this->_typename == 'rank') {
				$RANK[$arid]['linkurl'] = $this->_genUrl($pLevel, $rank);
				$sql .= ",linkurl='{$RANK[$arid]['linkurl']}'";
			}

			$sql = "UPDATE {$this->_table} SET $sql WHERE arid=$arid";
			$this->_db->query($sql);
			if ($arrparentid) {
				$arr = explode(',', $arrparentid);
				foreach ($arr as $a) {
					if ($a == 0) continue;
					isset($childs[$a]) or $childs[$a] = '';
					$childs[$a] .= ',' . $arid;
				}
			}
		}
		foreach ($RANK as $arid => $rank) {
			if (isset($childs[$arid])) {
				$RANK[$arid]['arrchildid'] = $arrchildid = $arid . $childs[$arid];
				$RANK[$arid]['child']      = 1;
				$this->_db->query("UPDATE {$this->_table} SET arrchildid='$arrchildid',child=1 WHERE arid='$arid'");
			} else {
				$RANK[$arid]['arrchildid'] = $arid;
				$RANK[$arid]['child']      = 0;
				$this->_db->query("UPDATE {$this->_table} SET arrchildid='$arid',child=0 WHERE arid='$arid'");
			}
		}
		$this->cache($RANK);
		return true;
	}

	/**
	 * 更新URL时候生成URL
	 * @param $level
	 * @param $info
	 * @return string
	 */
	private function _genUrl($level, $info) {
		switch ($level) {
			case 0:
				return url('auto/brand', 'brandId=' . $info['arid']);
				break;
			case 1:

				return url('auto/model', 'modelid=' . $info['arid']);
				break;
			case 2:
				return url('auto/car', 'carid=' . $info['arid']);
				break;
		}
		return '';

	}

	/**
	 * 获取父ids
	 * @param $arid
	 * @param $RANK
	 * @return string
	 */
	function getArrParentid($arid, $RANK) {
		if ($RANK[$arid]['parentid'] && $RANK[$arid]['parentid'] != $arid) {
			$parents = array();
			$cid     = $arid;
			while ($arid) {
				if ($RANK[$cid]['parentid']) {
					$parents[] = $cid = $RANK[$cid]['parentid'];
				} else {
					break;
				}
			}
			$parents[] = 0;
			return implode(',', array_reverse($parents));
		} else {
			return '0';
		}
	}

	/**
	 * 获取子元素id
	 * @param $arid
	 * @param $RANK
	 * @return string
	 */
	function getArrChildid($arid, $RANK) {
		$arrchildid = '';
		foreach ($RANK as $category) {
			if (strpos(',' . $category['arrparentid'] . ',', ',' . $arid . ',') !== false) $arrchildid .= ',' . $category['arid'];
		}
		return $arrchildid ? $arid . $arrchildid : $arid;
	}

	/**
	 * 获取某一级别下所有车系
	 * @param $id
	 * @return string
	 */
	public static function getCarbylevel($id=1) {
		global $db;
		$level = PCache::read('autoCategory-level.php');
		switch($id){
			case 1://乘用车
				$ars = $level[433]['arrchildid'];
				break;
			case 2://商用车
				$ars = $level[434]['arrchildid'];
				break;
			case 3://房车
				$ars = $level[435]['arrchildid'];
				break;
			case 4://新能源
				$ars = AutoCategory::getCacheItem(AutoCategory::TYPE_ENGINE, AutoCategory::TYPE_RANK_NEWENERGY, 'arrchildid');
				$result = $db->getAll("select  distinct arcid from {$db->getPre()}auto_model where enginetype in (".$ars.")");
				break;
			default:
				$ars = $level[$id]['arrchildid'];
		}
		if(!$result){
			$result = $db->getAll("select  distinct arcid from {$db->getPre()}auto_model where acid in (".$ars.")");
		}
		$cars = array();
		foreach($result as $t){
			$cars[] = $t['arcid'];
		}
		$cars = implode(',',array_filter($cars));
		$cars = $cars ? $cars : $id;
		return $cars;
	}

	/**
	 * 获取目录
	 * @param     $nickname
	 * @param int $arid
	 * @return string
	 */
	function getNickname($nickname, $arid = 0) {
		if (preg_match("/^[0-9a-z_\-\/]+$/i", $nickname)) {
			$condition = "nickname='$nickname'";
			if ($arid) $condition .= " AND arid!=$arid";
			$r = $this->_db->getOne("SELECT arid FROM {$this->_table} WHERE $condition");
			if ($r) {
				return '';
			} else {
				return $nickname;
			}
		} else {
			return '';
		}
	}


//	/**
//	 * 获取displacement的Sql语句
//	 * @param $sql
//	 * @return string
//	 */
//	public function getDisplacementSql($sql) {
//		$arr=$this->_db->getAll($sql);
//		foreach($arr as $val) {
//			$id[] = $val['amid'];
//		}
//		$strid = implode(",", $id);
//		$strid = " and amid in ($strid)";
//		return $strid;
//	}

	/**
	 * 获取筛选后的车款数组
	 * @param $sql
	 * @return array
	 */
	public function getModul($sql) {
		//获取车款的唯一车系id
		$arrDistinct = $this->_db->getAll($sql);
		//找到车系数据
		foreach ($arrDistinct as $key => $val) {
			$arid          = $val['arcid'];
			$arrAuto[$key] = $this->_db->getOne("select * from {$this->_table} where arid=$arid");

		}
		return $arrAuto;
	}


	/**
	 * 获取name
	 * @param $name
	 * @return array|null
	 */
	public function getName($name) {
		return $this->_db->getOne("select name from {$this->_table} where arid=$name");
	}

	/**
	 * 过滤二维数组的重复值
	 * @param      $arr
	 * @param bool $stkeep
	 * @param bool $ndformat
	 * @return mixed
	 */
	function uniqueArr($arr, $stkeep = false, $ndformat = true) {
		if ($stkeep) $stArr = array_keys($arr);
		if ($ndformat) $ndArr = array_keys(end($arr));
		foreach ($arr as $v) {
			$v      = join(",", $v);
			$temp[] = $v;
		}
		$temp = array_unique($temp);
		foreach ($temp as $k => $v) {
			if ($stkeep) $k = $stArr[$k];
			if ($ndformat) {
				$tempArr = explode(",", $v);
				foreach ($tempArr as $ndkey => $ndval) {
					$output[$k][$ndArr[$ndkey]] = $ndval;
				}
			} else $output[$k] = explode(",", $v);
		}
		return $output;
	}


	/**
	 * 缓存数据
	 * @param array $data
	 */
	function cache($data = array()) {
		if ($this->_typename == AutoCategory::TYPE_RANK) {
			foreach ($data as $k => $v) {
				if ($v['level'] > 1) {
					unset($data[$k]);
				}
			}
		}
		PCache::sysAutoCategory($this->_typename, $data);
	}
}